package org.openrbac.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.openrbac.rbac.constant.CommonConstant;
import org.openrbac.rbac.entity.Auth;
import org.openrbac.rbac.mapper.AuthMapper;
import org.openrbac.rbac.mapper.UserMapper;
import org.openrbac.rbac.service.AuthService;
import org.openrbac.rbac.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author bapie
* @description 针对表【auth(系统菜单)】的数据库操作Service实现
* @createDate 2024-04-03 15:37:15
*/
@Service
public class AuthServiceImpl extends ServiceImpl<AuthMapper, Auth>
    implements AuthService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public Auth getById(int id) {
        return this.baseMapper.selectAuthById(id);
    }


    /**
     * 分页查询
     * @param current
     * @param size
     * @param sort
     * @param name
     * @param isHidden
     * @param createTime
     * @return
     */
    public IPage<Auth> getPageAuths(long current, long size, String sort, String name, Boolean isHidden, String createTime) {
        Page<Auth> page = new Page<>(current, size);
        QueryWrapper wrapper = new QueryWrapper<>();

        // 设置排序条件
        if ("desc".equals(sort)) {
            wrapper.orderByDesc("create_time");
        } else {
            // 如果没有指定desc，则默认升序
            wrapper.orderByAsc("create_time");
        }

        // 如果name不为空，则添加name条件
        if (name != null && !name.isEmpty()) {
            wrapper.like("name", name);
        }

        // 如果isHidden不为空，则添加isHidden条件
        if (isHidden != null && !createTime.isEmpty()) {
            wrapper.eq("is_hidden", isHidden);
        }

        if(createTime != null && !createTime.isEmpty()){
            System.out.println(createTime.substring(0, 10));
            wrapper.like("create_time", createTime.substring(0, 10));
        }
        return this.baseMapper.selectPage(page, wrapper);
    }

    /**
     * 批量删除权限
     * @param id
     * @return
     */
    @Override
    public boolean delAuth(List<Long> id) {
        if(id.size()==0){
            return false;
        }
//        int result = this.baseMapper.delAuthByIds(id);
        int result = this.baseMapper.deleteBatchIds(id);
        if(result>0){
            return this.baseMapper.delRoleAuthByAuthIds(id) > 0;
        }else {
            return false;
        }
    }

    /**
     * 修改权限内容
     * @param auth
     * @return
     */
    public boolean editAuth(Auth auth) {
        if(Objects.isNull(auth)){
            return false;
        }
        return this.baseMapper.updateById(auth) > 0;
    }

    /**
     * 添加权限
     * @param auth
     * @return
     */
    public boolean addAuth(Auth auth) {
        if(Objects.isNull(auth)||auth.getUri().isEmpty()||auth.getName().isEmpty()){
            return false;
        }
        return this.baseMapper.insert(auth) > 0;
    }

    @Override
    public List<Auth> findAuths(String username) {
        if(username != null && !username.isEmpty()){
            return this.baseMapper.listAuthByRoleIds(
                    userMapper.listRoleIdsByUserId(
                            userMapper.selectIdByUsername(username)));
        }
        return null;
    }

    //获取路由信息
    @Override
    public List<Auth> getRouters(String web) {
        List<Auth> firstRouters = new ArrayList<>();
        List<Auth> auths = new ArrayList<>();
        try{
            Map<Object, Object> auth_result = redisUtil.hashGetAll(CommonConstant.AUTHS);

            auth_result.forEach((k, v) -> {
                Auth auth = (Auth) v;
                auths.add(auth);
            });

            firstRouters = auths.stream()
                    .filter(auth -> auth.getPath()!= null && auth.getPath().equals(web))
                    .collect(Collectors.toList());

            Set<Auth> uniqueAuths = new HashSet<>(auths);
            firstRouters.forEach(auth1 -> {
                List<Auth> children = auths.stream()
                        .filter(auth2 -> Objects.equals(auth2.getPid(), auth1.getId()))
                        .map(auth2 -> getRoutersChildren(auth2, uniqueAuths))
                        .collect(Collectors.toList());
                auth1.setChildren(children);
                    }
            );
        }catch (Exception e){
            log.error(String.valueOf(e));
            log.error("获取路由失败");
        }

        return firstRouters;
    }

    //将三级路由添加到二级路由中
    private Auth getRoutersChildren(Auth auth,Set<Auth> auths) {
        List<Auth> children = new ArrayList<>();
        auths.stream()
                .filter(auth1 -> Objects.equals(auth1.getPid(), auth.getId()))
                .forEach(auth1 -> {
                    children.add(auth1);
                });
        auth.setChildren(children);
        return auth;
    }
}




